<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ page import="java.io.*"%>
<%@ page import="java.util.*"%>
<%@ page import="javax.xml.parsers.*,javax.xml.transform.*,javax.xml.transform.dom.*,javax.xml.transform.stream.*,org.w3c.dom.*,org.xml.sax.*"%>
<%@ page import="java.net.*"%>
<%
	String strName = URLDecoder.decode(request.getParameter("name"), "utf-8"); //解码点评用户名称
	String strContent = URLDecoder.decode(request.getParameter("content"), "utf-8"); //解码点评提交内容
	String realPath = request.getSession().getServletContext().getRealPath("/jQuery/chapter6/");
	String fileName = realPath+"/CommentData.xml";
	File fileTest = new File(fileName);
	DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
	DocumentBuilder builder = null;
	try {
		builder = factory.newDocumentBuilder();
	} catch (ParserConfigurationException e1) {
		e1.printStackTrace();
	}
	Document document = null;
	Node comment = null;
	if(fileTest.exists()){ 
        document = builder.parse(fileTest);
        comment = document.getElementsByTagName("Comment").item(0);
	}else{
		document = builder.newDocument();
		comment = document.createElement("Comment");//创建根节点
		document.appendChild(comment);
	}
	
	Element data = document.createElement("Data");
	comment.appendChild(data);
	Element name = document.createElement("name");
	name.appendChild(document.createTextNode(strName));
	Element content = document.createElement("content");
	content.appendChild(document.createTextNode(strContent));
	Element date = document.createElement("date");
	date.appendChild(document.createTextNode(new Date().toLocaleString()));
	data.appendChild(name);
	data.appendChild(content);
	data.appendChild(date);

	//将DOM对象document写入到xml文件中
	TransformerFactory tf = TransformerFactory.newInstance();
	try {
		Transformer transformer = tf.newTransformer();
		DOMSource source = new DOMSource(document);
		if(!fileTest.exists()){
			transformer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		}
		transformer.setOutputProperty(OutputKeys.INDENT, "yes");
		FileOutputStream file = new FileOutputStream(fileTest,false);
		Writer outStreamWriter = new OutputStreamWriter(file,"utf-8");
		PrintWriter pw = new PrintWriter(outStreamWriter);
		StreamResult result = new StreamResult(pw);
		transformer.transform(source, result); //关键转换
		System.out.println("生成XML文件成功!");
	} catch (TransformerConfigurationException e) {
		System.out.println(e.getMessage());
	} catch (IllegalArgumentException e) {
		System.out.println(e.getMessage());
	} catch (FileNotFoundException e) {
		System.out.println(e.getMessage());
	} catch (TransformerException e) {
		System.out.println(e.getMessage());
	}
	out.print("您的点评已成功发表！");
%>